package com.guoxin.designpattern.chapter7;


import java.util.stream.IntStream;

/**
 * 不可变对象性能测试
 *
 * @author guoxin
 * @date 2019/9/5
 */
public class ImmutablePerformance {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        //407
        SyncObj syncObj = new SyncObj();
        syncObj.setName("Tom");
        IntStream.range(0,10000000).forEach(i-> syncObj.toString());
        long endTime = System.currentTimeMillis();
        System.out.println("Elapsed time "+(endTime-startTime));

        //99
        long startTime2 = System.currentTimeMillis();
        ImmutableObj immutableObj = new ImmutableObj("Rose");
        IntStream.range(0,10000000).forEach(i-> immutableObj.toString());
        long endTime2 = System.currentTimeMillis();
        System.out.println("Elapsed time "+(endTime2-startTime2));
    }
}

final class ImmutableObj {
    private final String name;

    ImmutableObj(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "[" + name + "]";
    }
}

class SyncObj {
    private String name;

    public synchronized void setName(String name) {
        this.name = name;
    }

    @Override
    public synchronized String toString() {
        return "[" + name + "]";
    }
}